<template lang="">
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索框和添加用户按钮 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUsersDialog = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" stripe style="width: 100%" :border="true">
        <el-table-column
          type="index"
          label="序号"
          width="60px"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="openDelUserView(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="roleassignment(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addUsersDialog"
        width="50%"
        @close="addUsersDialogClosed"
      >
        <!-- 内容区 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUsersDialog = false">取 消</el-button>
          <el-button type="primary" @click="addUser">
            确 定
          </el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editUserDialog"
        width="50%"
        @close="editUsersDialogClosed"
      >
        <!-- 内容区 -->
        <el-form
          :model="editUser"
          :rules="editUserRules"
          ref="editUserRef"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserName" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUser.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="editCommit">
            确 定
          </el-button>
        </span>
      </el-dialog>

      <!-- 分配橘色对话框 -->
      <el-dialog title="提示" :visible.sync="roleassignmentDialog" width="50%">
        <div>
          <p>当前的用户为：{{ userInfo.username }}</p>
          <p>当前的角色为：{{ userInfo.role_name }}</p>
        </div>
        分配新角色：
        <el-select v-model="selectRoleID" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleassignmentDialog = false">取 消</el-button>
          <el-button type="primary" @click="AssignUserRoles">
            确 定
          </el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    //验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号！'))
    }
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱的正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱！'))
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      //用户列表和总数
      userList: [],
      total: 0,
      addUsersDialog: false, //控制对话框开关
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3~10个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在6~15个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //修改用户信息对话框开关
      editUserDialog: false,
      //修改用户信息的对象
      editUser: {
        email: '',
        mobile: ''
      },
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机！', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserName: '',
      editUserId: 0,
      delUserDialog: false,
      delUserId: 0,
      //分配角色对话框开关
      roleassignmentDialog: false,
      userInfo: {}, //被分配角色用户的对象
      roleList: [], //角色列表
      selectRoleID: ''
    }
  },
  methods: {
    //获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get(`users`, {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    //监听页码size的变动
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    //监听页码变动
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听用户状态变化
    async userStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/` + userInfo.id + `/state/` + userInfo.mg_state
      )
      console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    //添加用户对话框关闭事件
    addUsersDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        //发起用户请求
        const { data: res } = await this.$http.post(`users`, this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功！')
        this.addUsersDialog = false
        this.getUserList()
      })
    },
    //打开修改用户信息的对话框
    async showEditDialog(id) {
      //提交数据请求，请求用户信息
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户信息失败')
      this.editUserDialog = true
      //将内容保存到本地
      this.editUserName = res.data.username
      this.editUser.mobile = res.data.mobile
      this.editUser.email = res.data.email
      this.editUserId = id
    },
    //关闭修改用户信息对话框
    editUsersDialogClosed() {
      this.$refs.editUserRef.resetFields()
    },
    //提交编辑用户请求
    async editCommit() {
      //预验证
      const valid = this.$refs.editUserRef.validate(valid => {
        return valid
      })
      if (valid) {
        const { data: res } = await this.$http.put(
          `users/${this.editUserId}`,
          this.editUser
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editUserDialog = false
      } else {
        this.$message.error('请输入正确格式')
      }
    },
    //删除用户
    openDelUserView(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          //状态码不是200则报错
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          this.$message.success(res.meta.msg)
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //获取角色列表
    async roleassignment(userInfo) {
      this.userInfo = userInfo
      //获取角色列表
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
        return
      }

      this.roleList = res.data
      this.roleassignmentDialog = true
    },
    //分配角色
    async AssignUserRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectRoleID
        }
      )
      // console.log(this.selectRoleID)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }

      //分配用户角色成功
      this.$message.success(res.meta.msg)

      //重新获取用户列表
      this.getUserList()

      //关闭对话框
      this.roleassignmentDialog = false
    }
  }
}
</script>
<style lang=""></style>
